package com.adong.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author adong
 */
public class JdbcUtils {
    private static DruidDataSource druidDataSource;
    private static ThreadLocal<Connection> conns = new ThreadLocal<Connection>();

    static {
        try {
            //创建配置文件
            Properties pros = new Properties();
            //通过反射读取配置文件
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            pros.load(is);
            //创建数据库连接池
            druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(pros);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private JdbcUtils() {

    }

    /**
     * 获取连接池中连接
     *
     * @return 返回连接对象
     */
    public static Connection getConnection() {
        Connection conn = conns.get();
        if (conn == null) {
            try {
                conn = druidDataSource.getConnection();
                conns.set(conn); //保存到ThreadLocal中
                conn.setAutoCommit(false);//设置为手动提交
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return conn;

    }

    public static void commitAndClose() {
        Connection connection = conns.get();
        if (connection != null) { //不为空表示操作了数据库
            try {
                connection.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //一定要使用remove关闭,tomcat底层使用了线程池操作
        conns.remove();
    }

    public static void rollbackAndClose() {
        Connection connection = conns.get();
        if (connection != null) { //不为空表示操作了数据库
            try {
                connection.rollback(); //回滚事务
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        conns.remove();
    }

    @Deprecated
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

}
